import { appExists, appList, appAdd, appDelete, appUpdate } from '../scripts/api'
// 后端异步验证
const validatorAppName = (rule, value, callback) => {
  if (!value) {
    callback(new Error('应用名称不能为空(前端验证)'))
  } else {
    appExists(value).then(response => {
      if (response.data) {
        callback(new Error('应用名称已经存在(后端验证)'))
      } else {
        callback()
      }
    }).catch(e => {
      callback(new Error('应用名称验证失败'))
    })
  }
}
// 前端静态验证
const validatorIp = (rule, value, callback) => {
  const reg = new RegExp('(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)')
  if (!reg.test(value)) {
    callback(new Error('IP格式不正确'))
  } else {
    callback()
  }
}

export default {
  provide () {
    return {
      $BtnExtends: {
        formValidate: {
          date: {
            router: false
          }
        }
      }
    }
  },
  data () {
    return {
      selectedItems: [],
      modalShow: false,
      modalFlag: true,
      modalForm: {
        id: '',
        ip: '',
        appName: '',
        appType: '',
        noticeType: []
      },
      ruleModalForm: {
        appName: [
          { required: true, validator: validatorAppName, trigger: 'blur' }
        ],
        ip: [
          { required: true, validator: validatorIp, trigger: 'blur' }
        ]
      },
      openClose: false,
      formValidate: {
        ip: '',
        appName: '',
        appType: '',
        alarmLevel: '1',
        ipType: 2,
        instanceMin: 0,
        instanceMax: 100,
        // date: [],
        startTime: '',
        endTime: '',
        noticeType: ['1', '2'],
        alarmSwitch: true
      },
      ruleValidate: {
        appName: [
          { required: true, message: '应用名称不能为空', trigger: 'blur' }
        ],
        ip: [
          { validator: validatorIp, trigger: 'blur' }
        ]
      },
      table: {
        tData: (pageParam) => {
          Object.assign(pageParam, this.formValidate)
          return appList({
            params: pageParam
          })
        },
        tColumns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            type: 'expand',
            width: 50,
            extendFormat: 'expand',
            align: 'center',
            expand: (params) => {
              if (params) {
                const list = [
                  { title: this.$t('table.selectTable.appName'), key: 'appName' },
                  { title: this.$t('table.selectTable.appType'), key: 'appType' },
                  { title: '告警级别', key: 'alarmLevel' },
                  { title: '通知类型', key: 'noticeType' }
                ]
                return { list: list, columns: 3 }
              }
            }
          },
          {
            title: this.$t('table.selectTable.appName'),
            key: 'appName',
            minWidth: 120,
            align: 'center',
            sortable: true
          },
          {
            title: this.$t('table.selectTable.appType'),
            key: 'appType',
            minWidth: 120,
            align: 'center',
            mapColor: {
              tomcat: '#2d8cf0',
              java: '#19be6b'
            }
          },
          {
            title: '告警级别',
            key: 'alarmLevel',
            minWidth: 120,
            sortable: true,
            align: 'center',
            mapColor: {
              调试: '#2d8cf0',
              通知: '#19be6b',
              警告: '#f90',
              严重: '#ed4014',
              紧急: '#d83b81'
            },
            renderType: 'outline'
          },
          {
            title: '通知类型',
            key: 'noticeType',
            minWidth: 120,
            align: 'center',
            sortable: true
          },
          {
            title: '实例数',
            key: 'instance',
            sortable: true,
            minWidth: 120,
            align: 'center',
            extendFormat: 'number'
          },
          {
            title: '修改时间',
            key: 'updateDate',
            minWidth: 160,
            align: 'center',
            extendFormat: 'relativeTime'
          },
          {
            title: '创建时间',
            key: 'date',
            width: 160,
            align: 'center',
            extendFormat: 'date'
          },
          {
            title: '操作',
            minWidth: 120,
            align: 'center',
            slot: 'action'
          }
        ]
      },
      appTypeList: [
        { code: 'java', text: 'java' },
        { code: 'tomcat', text: 'Tomcat' }
      ],
      ipSearchList: [
        { code: '1', text: '精准查询' },
        { code: '2', text: '模糊查询' }
      ]
    }
  },
  methods: {
    selectItem (selection) {
      this.selectedItems = selection
    },
    btnSearch (v) {
      if (v) {
        this.$refs['dataTable'].reload()
      }
    },
    formModalClick (Proxy) {
      switch (this.modalFlag) {
        case 'create':
          this.modalSubmit(Proxy); break
        case 'update':
          this.modalUpdate(Proxy); break
        case 'batchUpdate':
          this.modalBatchUpdate(Proxy); break
      }
    },
    modalSubmit (Proxy) {
      const { id, ...param } = this.modalForm // 排除id属性进行提交
      Proxy(appAdd(param)).then(response => {
        console.log('=Create=应用新增成功==', response.data)
      })
    },
    modalUpdate (Proxy) {
      const { ip, appName, ...param } = this.modalForm
      Proxy(appUpdate(param))
    },
    modalBatchUpdate (Proxy) {
      const { appType, noticeType } = this.modalForm
      const _ids = this.$refs['dataTable'].getSelected().flatMap(x => x.id) // 获取勾选中的id
      Proxy(appUpdate({ ids: _ids, appType, noticeType })).then(response => {
        console.log('=Update Batch=应用批量修改成功==', response.data)
      })
    },
    beforeBtnBatchUpdate () {
      const selected = this.$refs['dataTable'].getSelected()
      if (selected.length === 0) {
        this.$Message.error('请勾选要修改的项!')
      } else {
        this.modalShow = true
        this.modalFlag = 'batchUpdate'
        return false
      }
    },
    beforeBtnBatchDelete () {
      if (this.$refs['dataTable'].getSelection().length === 0) {
        this.$Message.error('请勾选要删除的项!')
      } else {
        return true
      }
    },
    btnBatchDelete (bool, Proxy) {
      if (bool) {
        const _ids = this.$refs['dataTable'].getSelected().flatMap(x => x.id)
        Proxy(appDelete({ ids: _ids })).then(response => {
          console.log('=Delet Batch=应用批量删除成功==', response.data)
        })
      }
    },
    exportData () {
      this.$refs['dataTable'].exportCsv({
        filename: 'The original data'
      })
    },
    formModalBeforeClick () {
      if (this.modalFlag === 'detail') {
        this.modalShow = false
      } else {
        return true
      }
    },
    beforeBtnUpdate (row) {
      this.modalShow = true
      this.modalFlag = 'update'
      let { id, appName, ip, appType, noticeType } = row
      noticeType = [noticeType]
      Object.assign(this.modalForm, { id, appName, ip, appType, noticeType })
    },
    btnDelete (Proxy, id) {
      Proxy(appDelete({ ids: id }))
    },
    btnIcon (row, index) {
      this.modalShow = true
      this.modalFlag = 'detail'
      let { id, appName, ip, appType, noticeType } = row
      noticeType = [noticeType]
      Object.assign(this.modalForm, { id, appName, ip, appType, noticeType })
      // alert('索引：' + index + ';\n值：' + JSON.stringify(row))
    },
    handleClick (rowObj) {
      this.$Message.success('detail:' + JSON.stringify(rowObj))
    }
  }
}
